package com.swdegao.iot.netty.udp.server.guoxinudp;


import com.swdegao.iot.netty.entity.*;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import com.alibaba.fastjson.JSON;
import com.swdegao.iot.SwdegaoIotMgtServerApplication;
import com.swdegao.iot.netty.utils.RedisUtils;

/**
 * 用于存储数据包、更新redis中数据
 * @Author:只会走路的小鸟
 * @Date: Created in 8:20 2018\10\26 0001
 */
public class GuoXinUdpSaveMessgaeHandler extends SimpleChannelInboundHandler<HandlerMessage> {

	@Autowired
    private RedisUtils redisUtils = SwdegaoIotMgtServerApplication.getBean(RedisUtils.class);
	//定义一个全局的记录器，通过LoggerFactory获取
    private final static Logger logger = LoggerFactory.getLogger(GuoXinUdpSaveMessgaeHandler.class);

	@Override
	protected void channelRead0(ChannelHandlerContext cxt, HandlerMessage msg) throws Exception {
		String imei = msg.getImei();
		CallBackData callBackData = new CallBackData();
		try {


			UpData upData = new UpData();
			long nowtime = System.currentTimeMillis();
			upData.setCreatetime(nowtime);
			upData.setImei(imei);


		    upData.setUpData(msg.getRecevieMsgStr());
			//String callbackUrl = "";
			//imei信息以hash形式存储（key,hashkey,value）
			if(redisUtils.hmhave(Parameter.imei_info,imei)){//已经存储

				ImeiInfo imeiInfo = JSON.parseObject(redisUtils.hmGet(Parameter.imei_info,imei).toString(), ImeiInfo.class);
				msg.setApplicationSubscribe(imeiInfo.getApplicationSubscribe());//订阅的信息
				//callbackUrl = (imeiInfo.getApplicationSubscribe()!=null&&imeiInfo.getApplicationSubscribe().size()>0) ? imeiInfo.getApplicationSubscribe().get(0).getCallbackurl().toString() : "";

			}else{
				//直接往hash中添加
				ImeiInfo imeiInfo = new ImeiInfo();
				imeiInfo.setOnlineLastTime(nowtime);
				imeiInfo.setOnlineStatus("1");
				imeiInfo.setcType("UDP");
				imeiInfo.setImei(imei);
				imeiInfo.setOutTime(Parameter.outtime_hear);
				imeiInfo.setHeartbeat_registered_num(0);
				imeiInfo.setHeartbeat_delay_num(0);
				//msg.setApplicationSubscribe(imeiInfo.getApplicationSubscribe());
				redisUtils.hmSet(Parameter.imei_info, imei, JSON.toJSONString(imeiInfo));
			}

			//redisUtils.lPush(imei+Parameter.imei_info_updata,JSON.toJSONString(upData));//存储所有updata数据
			//将推送数据存储到redis中
			try {

				callBackData.setImei(imei);
				callBackData.setCreatetime(nowtime);
				callBackData.setUpData(upData.getUpData());
			} catch (Exception e) {
				// TODO: handle exception
			}

		} catch (Exception e) {
			// TODO: handle exception
			logger.error(imei+"#######"+e.getMessage());
		}

	//将message继续往下传递
		cxt.fireChannelRead(callBackData);
	}

	@Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { // (7)
	    	Channel incoming = ctx.channel();
			logger.info("client "+incoming.remoteAddress()+"异常"+cause.getMessage());
	        // 当出现异常就关闭连接
	        cause.printStackTrace();
	        //ctx.close();
	    }

}
